//
//  TFDataCaptureManager.m
//  WeChatBuniess
//
//  Created by Guo Rui on 2017/12/22.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "TFDataCaptureManager.h"
#import "WCBDataHelper.h"
#import "YYModel.h"
#import "WCASessionManager.h"
#import "WCAHTTPRequestSerializer.h"
#import "WCMediaItem.h"
#import "TFToast.h"

@interface TFDataCaptureManager ()
@property (strong, nonatomic, readwrite) TFDataCapturer                 *capturer;
@property (nonatomic, strong, readwrite) NSMutableSet                   *uploadedItemIdsSet;
@property (strong, nonatomic, readwrite) NSMutableArray<NSDictionary *>   *failArray;
@property (assign,nonatomic) NSInteger receiveDataSuccessCount;
@property (strong, nonatomic) dispatch_queue_t serialQueue;
@end


@implementation TFDataCaptureManager

//MARK: - init
+ (instancetype)sharedInstance
{
    static TFDataCaptureManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TFDataCaptureManager alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.capturer = [TFDataCapturer new];
        self.uploadedItemIdsSet = [NSMutableSet new];
        self.failArray = [NSMutableArray new];
        self.receiveDataSuccessCount = 0;
        self.serialQueue = dispatch_queue_create("cn.timeface.wechatbuniess.tfdatacapturemanager.queue", NULL);
        [self achieveCpatureBlock];
    }
    return self;
}

- (void)achieveCpatureBlock {
    __weak TFDataCaptureManager * weakself = self;
    self.capturer.SendDataPer20Block = ^(NSArray<WCDataItem *> *dataArray,NSInteger allReceiveDataCount) {
        NSLog(@"接收数量回调:%zd",allReceiveDataCount);
        if (weakself.reciveCountBlock) {//接收数量回调
            weakself.reciveCountBlock(allReceiveDataCount);
        }
        if (weakself.capturer.captureCompleted&&weakself.reciveDataCompletion) {//接收完成回调
            weakself.reciveDataCompletion();
        }
        
        [weakself uploadCaptureData:dataArray];
    };
}

//MARK: - handleData
- (void)saveUploadDataInfo:(NSArray<WCDataItem *> *)dataArray uploadSuccessed:(BOOL)success {
    //数据同步
    dispatch_async(_serialQueue, ^{
        //结果回调
        self.receiveDataSuccessCount += dataArray.count;
        if (success) {
            NSLog(@"上传成功数量回调:%zd",self.receiveDataSuccessCount);
        }
        if (success&&self.sendSuccessCountBlock) {//上传成功数量回调
            self.sendSuccessCountBlock(self.receiveDataSuccessCount);
        }
        if (!success) {
            [self.failArray addObjectsFromArray:[self dictArrayForRequest:dataArray]];
            NSLog(@"上传失败数量回调:%zd",self.failArray.count);
            if (self.sendFailCountBlock) {//上传失败数量回调
                self.sendFailCountBlock(self.failArray.count);
            }
        }
        [dataArray enumerateObjectsUsingBlock:^(WCDataItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.uploadedItemIdsSet addObject:item.itemId];
        }];
        //判断是否发送完成
        if (self.capturer.captureCompleted&&[self.capturer.itemIdsSet isEqualToSet:self.uploadedItemIdsSet]) {
            NSLog(@"数据全部上传完成，其中包括失败数据:%zd条",self.failArray.count);
            [self uploadCompletedRequest];
            if (self.sendDataCompletion) {//上传完成回调
                self.sendDataCompletion(self.failArray.count, self.failArray.copy);
            }
        }
    });
    
}

//MARK: - dataRequest
- (void)uploadCaptureData:(NSArray *)datas
{
    NSArray *dictArray = [self dictArrayForRequest:datas];
    NSDictionary *dict = @{ @"data" : [dictArray yy_modelToJSONString],
                            @"from" : @3,
                            @"type" : @0,
                            // TODO: 修改
                            @"wechatId" : @"xytgr12",
                            @"wechatUserName" : @"郭睿",
//                            @"wechatId" : self.contact.m_nsUsrName,
//                            @"wechatUserName" : self.contact.m_nsNickName
                            };
    
    __weak TFDataCaptureManager * weakself = self;
    WCAJSONRequestSerializer *serializer = [WCAJSONRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    [WCASessionManager POST:@"tf_wx/mtime/addPartTime" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSString *code = responseObject[@"code"];
        [weakself saveUploadDataInfo:datas uploadSuccessed:[code isEqualToString:@"000"]];
        NSString *message = nil;
        NSString *messageForUser = nil;
        BOOL success = NO;
        if ([code isEqualToString:@"000"]) {
            message = @"发送成功";
            messageForUser = @"发送成功";
            success = YES;
        }
        else if ([code isEqualToString:@"TM001001"]) {
            message = @"请求参数不正确";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001002"]) {
            message = @"数据异常";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001003"]) {
            message = @"时光ID不存在";
            messageForUser = @"发送失败，请重试";
        }
        else if ([code isEqualToString:@"TM001004"]) {
            message = @"用户没有发起微信数据导入";
            messageForUser = @"发送失败，请重试";
        }
        
        if (message) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [TFToast toast:message];
            });
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [weakself saveUploadDataInfo:datas uploadSuccessed:NO];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *messageForUser = @"您的网络不给力，请重试";
            [TFToast toast:messageForUser];
        });
    }];
}

- (void)uploadCompletedRequest {
    WCAHTTPRequestSerializer *serializer = [WCAHTTPRequestSerializer serializer];
    [WCASessionManager setRequestSerialization:serializer];
    [WCASessionManager POST:@"tf_wx/mtime/wxSendDoneNotify"
                 parameters:@{
                              // TODO: 修改
                              @"wechatId" : @"xytgr12",
                              @"wechatUserName" : @"郭睿",
                              //                            @"wechatId" : self.contact.m_nsUsrName,
                              //                            @"wechatUserName" : self.contact.m_nsNickName
                              
                              }
                    success:^(NSURLSessionDataTask *task, id responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([[responseObject objectForKey:@"code"] isEqualToString:@"000"]) {
                [TFToast toast:@"上传完成通知~"];
            }
            else {
                 [TFToast toast:[responseObject objectForKey:@"code"]];
            }
        });
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [TFToast toast:error.localizedDescription];
        });
    }];
}

- (NSArray *)dictArrayForRequest:(NSArray *)datas{
    NSMutableArray *dictArray = [NSMutableArray arrayWithCapacity:0];
    for (WCDataItem *item in datas) {
        NSString *temp = [item.contentDesc stringByReplacingOccurrencesOfString:@"%" withString:@""];
        temp = [temp stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        temp = [temp stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"@_?=;!~*()+`#%^{}\":[].|\\<>- "].invertedSet];
        
        NSMutableArray *imgs = [NSMutableArray arrayWithCapacity:0];
        for(WCMediaItem *mediaItem in item.contentObj.mediaList) {
            [imgs addObject:mediaItem.dataUrl.url];
        }
        
        NSDictionary *dict = @{ @"content": temp,
                                @"date" : @(((NSTimeInterval)item.createtime) * 1000),
                                @"snsId": item.itemId,
                                @"userName": item.username,
                                @"type" : @(item.contentObj.type),
                                @"imgs" : imgs,
                                };
        [dictArray addObject:dict];
    }
    return dictArray;
}

//MARK: - cleanData
- (void)clean {
    [self.capturer clean];
    self.receiveDataSuccessCount = 0;
    [self.uploadedItemIdsSet removeAllObjects];
    [self.failArray removeAllObjects];
}
@end
